<template>
  <div class="message-container">
    <div ref="scrollContainer" class="message-content">
      <!-- {{ visibleMessages }} 
      aapppppppppppppppppppppppppppp
      {{ message }} -->
      <div v-for="(messageItem, index) in visibleMessages" :key="getMessageKey(messageItem, index)" class="message-item"
        :class="{ 'animate-in': index >= animationStartIndex }">
        <!-- 保持原有的消息内容结构 -->
        <div v-if="messageItem.type == 'text'" class="oneAnswer text"
          :class="{ 'question': messageItem?.role == 'user' }">
          <span>
            {{ messageItem.content }}
          </span>
        </div>
        <div v-else-if="messageItem.type == 'img1'" class="oneAnswer">
          <div class="img1 imgAnswer gallery">
            <div class="image-item" @click="showImagePreview(messageItem.symbolImage)"><img :src="messageItem.symbolImage" alt=""></div>
            <div class="image-item" @click="showImagePreview(messageItem.packageImage)"><img :src="messageItem.packageImage" alt=""></div>
          </div>
          <div class="mageFoot">
            <el-icon class="pointer" @click="setDownloadFile(messageItem?.taskId ?? 0, messageItem?.type ?? 0)">
              <Download />
            </el-icon>
          </div>
        </div>
        <template v-else-if="messageItem.type == 'json'">
          <div class="file1 fileAnswer oneAnswer">
            <div>
              <fileShow :fileName="messageItem.symbolJsonName" fileType="json"></fileShow>
            </div>
            <div>
              <fileShow :fileName="messageItem.packageJsonName" fileType="json"></fileShow>
            </div>
          </div>
          <div class="mageFoot">
            <el-icon class="pointer" @click="setDownloadFile(messageItem?.taskId ?? 0, messageItem?.type ?? 0)">
              <Download />
            </el-icon>
          </div>
        </template>

        <template v-else-if="messageItem.type == 'pdf'">
          <!-- {{ messageItem }} -->
          <div class="file2 fileAnswer oneAnswer" :class="{ 'questionfile': messageItem?.role == 'user' }">
            <fileShow :pointer="true" :fileName="messageItem?.filename ?? ''" fileType="pdf"
              @click="sendData(messageItem)"></fileShow>
          </div>
        </template>

        <div v-else-if="messageItem.type == 'img2'" class="oneAnswer">
          <div class="img2 imgAnswer gallery">
            <div class="image-item"
              v-for="imgSrc in [messageItem.image3D, messageItem.packageRendingImage, messageItem.symbolRendingImage]"
              :key="imgSrc" @click="showImagePreview(imgSrc)">
              <img :src="imgSrc" alt="">
            </div>
          </div>
          <div class="mageFoot">
            <el-icon class="pointer" @click="setDownloadFile(messageItem?.taskId ?? 0, messageItem?.type ?? 0)">
              <Download />
            </el-icon>
          </div>
        </div>
        <div v-else-if="messageItem.type == 'btu'" :class="{ lastBtu: messageItem.filetype == 'none' }">
          <liudongBtu :state="messageItem.state" :displayTexts="messageItem.displayTexts"
            :filetype="messageItem.filetype" @update:state="handleStateUpdate($event, messageItem)"
            @click="sendData(messageItem)">
          </liudongBtu>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, watch, nextTick, onMounted, onUnmounted } from 'vue'
import fileShow from '@/components/fileShowcard.vue'
import liudongBtu from '@/components/liudongBtu.vue'
import { downloadFile } from '@/api/modules/demo.js'

import { Download } from "@element-plus/icons-vue";
import { emitter } from '@/utils/emitter.js'
import { useImagePreview } from '../useImagePreview';
const { showImagePreview } = useImagePreview()

// 控制显示的消息数组（使用深拷贝）
const visibleMessages = ref([])
// 跟踪当前动画开始的位置
const animationStartIndex = ref(0)
// 动画计时器
const animationTimer = ref(null)
// 待显示的消息队列
const pendingMessages = ref([])
// 上一次处理的完整消息数组（用于比较变化）
const lastProcessedMessages = ref([])
// 标记是否已初始化
const isInitialized = ref(false)

// 深拷贝函数
const deepClone = (obj) => {
  if (obj === null || typeof obj !== 'object') return obj;
  if (obj instanceof Date) return new Date(obj);
  if (obj instanceof Array) return obj.map(item => deepClone(item));
  if (typeof obj === 'object') {
    const clonedObj = {};
    for (const key in obj) {
      if (obj.hasOwnProperty(key)) {
        clonedObj[key] = deepClone(obj[key]);
      }
    }
    return clonedObj;
  }
}

// 生成唯一key
const getMessageKey = (messageItem, index) => {
  return `${index}-${messageItem.type}-${messageItem.content?.substring(0, 10) || ''}-${messageItem.taskId || ''}`;
}

const sendData = (data) => {
  console.log("117ee", data);

  if (data.filetype == 'none') {

  } else if (data.filetype == 'img2' && data.state == 2) {

    emitter.emit('setRendering', data)

  } else {
    emitter.emit('update-data', data)
    emitter.emit('setRightStatus', true)
  }
}

const props = defineProps({
  message: {
    type: Array,
    required: true,
    default: () => []
  }
})

// 初始化函数
const initializeMessages = () => {
  if (props.message.length > 0 && visibleMessages.value.length === 0) {
    // 直接显示所有初始消息，不应用动画
    visibleMessages.value = deepClone(props.message);
    animationStartIndex.value = visibleMessages.value.length; // 所有消息都不需要动画
    lastProcessedMessages.value = deepClone(props.message);
    isInitialized.value = true;

    // 滚动到底部
    scrollToBottom();
  }
}

// 监听props.message的变化（使用深拷贝比较）
watch(() => deepClone(props.message), (newMessages, oldMessages) => {
  // 如果尚未初始化，先进行初始化
  if (!isInitialized.value && newMessages.length > 0) {
    initializeMessages();
    return;
  }

  // 如果消息队列不为空，说明有动画正在进行，先停止
  if (pendingMessages.value.length > 0) {
    pendingMessages.value = [];
    if (animationTimer.value) {
      clearTimeout(animationTimer.value);
      animationTimer.value = null;
    }
  }

  // 完全重新处理消息
  processAllMessages(newMessages);
}, { deep: true })

// 处理所有消息，检测变化并相应更新
const processAllMessages = (newMessages) => {
  const currentVisibleCount = visibleMessages.value.length;

  // 如果新消息数量少于当前显示的消息，说明有消息被删除了
  if (newMessages.length < currentVisibleCount) {
    visibleMessages.value = deepClone(newMessages);
    animationStartIndex.value = visibleMessages.value.length;
    lastProcessedMessages.value = deepClone(newMessages);
    return;
  }

  // 检查是否有现有消息被修改（不仅仅是新增）
  let hasModifications = false;
  const minLength = Math.min(currentVisibleCount, newMessages.length);

  for (let i = 0; i < minLength; i++) {
    if (JSON.stringify(newMessages[i]) !== JSON.stringify(lastProcessedMessages.value[i])) {
      hasModifications = true;
      break;
    }
  }

  // 如果有现有消息被修改，完全重置显示
  if (hasModifications) {
    visibleMessages.value = deepClone(newMessages);
    animationStartIndex.value = visibleMessages.value.length;
    lastProcessedMessages.value = deepClone(newMessages);
    return;
  }

  // 如果只是新增消息，添加到待显示队列
  if (newMessages.length > currentVisibleCount) {
    const newMessageCount = newMessages.length - currentVisibleCount;
    const newMessagesToAdd = newMessages.slice(currentVisibleCount);

    // 添加到待显示队列
    pendingMessages.value = [...pendingMessages.value, ...newMessagesToAdd];
    lastProcessedMessages.value = deepClone(newMessages);

    // 如果没有正在进行的动画，开始动画
    if (!animationTimer.value) {
      processMessageQueue();
    }
  }
}

// 处理消息队列，逐条显示消息
const processMessageQueue = () => {
  if (pendingMessages.value.length === 0) {
    animationTimer.value = null;
    return;
  }

  // 从队列中取出第一条消息
  const message = deepClone(pendingMessages.value[0]);
  pendingMessages.value = pendingMessages.value.slice(1);

  // 添加到可见消息列表
  visibleMessages.value.push(message);

  // 滚动到底部
  scrollToBottom();

  // 设置下一条消息的延迟
  animationTimer.value = setTimeout(() => {
    processMessageQueue();
  }, 500); // 每条消息显示间隔200ms
}

const FileTypeUrl = {
  img1: 'downloadPdfImage', json: 'downloadJson', img2: 'downloadRendingFile'
}
const setDownloadFile = (taskid, fileType) => {
  console.log("ep", taskid, FileTypeUrl[fileType]);

  downloadFile({ taskId: taskid }, FileTypeUrl[fileType])
}
const scrollContainer = ref(null)
let autoScrollEnabled = true

const scrollToBottom = () => {
  if (scrollContainer.value && autoScrollEnabled) {
    nextTick(() => {
      scrollContainer.value.scrollTop = scrollContainer.value.scrollHeight
    })
  }
}

// 状态按钮
const parentState = ref(0)
const handleStateUpdate = (newValue, messageItem) => {
  messageItem.state = newValue
}
const handleScroll = () => {
  if (!scrollContainer.value) return
  const { scrollTop, scrollHeight, clientHeight } = scrollContainer.value
  autoScrollEnabled = scrollHeight - (scrollTop + clientHeight) < 50
}

onMounted(() => {
  // 组件挂载时初始化消息
  initializeMessages();

  scrollToBottom()
  if (scrollContainer.value) {
    scrollContainer.value.addEventListener('scroll', handleScroll)
  }
})

// 组件卸载前清除计时器
onUnmounted(() => {
  if (animationTimer.value) {
    clearTimeout(animationTimer.value)
  }
})
</script>

<style scoped lang="scss">
.pointer {
  cursor: pointer;
}

.message-container {
  max-width: 48rem;
  margin-inline: auto;
}

.message-content {
  width: 100%;
}

.message-item {
  margin-bottom: 8px;
  margin-inline: auto;
  background: white;
  opacity: 1;
  transform: translateY(0);

  // 只有需要动画的消息项才会应用动画
  &:not(.animate-in) {
    transition: none;
  }

  &.animate-in {
    opacity: 0;
    transform: translateY(20px);
    transition: opacity 0.5s ease, transform 0.5s ease;
    animation: messageAppear 0.5s ease forwards;
  }
}

// 消息出现动画
@keyframes messageAppear {
  from {
    opacity: 0;
    transform: translateY(20px);
  }

  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.lastBtu {
  padding-bottom: 40px;
}

.imgAnswer {
  display: flex;

  &.img1 {
    div+div {
      margin-left: 8px;
    }
  }

  &>div {
    width: 380px;
    border-radius: 12px;
    overflow: hidden;
    border: 1px solid #EBEBEB;
    display: flex;
    justify-content: center;
    align-items: center;
    cursor: pointer;
  }

  &.img2 {
    div {
      width: 250px;
    }

    div+div {
      margin-left: 4px;
    }
  }

  img {
    width: 100%;
    display: block;
  }
}

.oneAnswer {
  padding-bottom: 12px;

  &.text {
    padding-bottom: 8px;
  }

  &.question {
    display: flex;
    justify-content: flex-end;

    &.text {
      padding-bottom: 40px;

      span {
        padding: 12px 16px;
        border-radius: 12px;
        background: #E8F0FC;
        font-size: 16px;
        font-weight: normal;
        line-height: 24px;
        color: #333333;
        display: inline-block;
        word-break: break-all;
      }
    }
  }

  &.questionfile {
    display: flex;
    justify-content: end;
  }
}

.mageFoot {
  padding-top: 12px;
}

.fileAnswer {
  &>div+div {
    margin-top: 8px;
  }
}

.gallery {
  // display: grid;
  // grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  // gap: 25px;
  // margin-top: 30px;
}

.image-item {
  background: white;
  border-radius: 15px;
  overflow: hidden;
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.1);
  transition: all 0.4s ease;
  opacity: 0;
  transform: translateY(30px);
  cursor: pointer;
  animation: fadeInUp 0.8s forwards;
}

.image-item:hover {
  transform: translateY(-10px);
  box-shadow: 0 5px 10px rgba(0, 0, 0, 0.1);
}

.image-item img {
  // width: 100%;
  // height: 220px;
  object-fit: cover;
  display: block;
  transition: transform 0.5s ease;
}

.image-item:hover img {
  transform: scale(1.05);
}

.image-info {
  padding: 20px;
}

.image-info h3 {
  color: #2c3e50;
  margin-bottom: 10px;
  font-size: 1.3rem;
}

.image-info p {
  color: #7f8c8d;
  line-height: 1.6;
}

/* 为每个图片设置不同的动画延迟 */
.image-item:nth-child(1) {
  animation-delay: 0.5s;
}

.image-item:nth-child(2) {
  animation-delay: 1.0s;
}

.image-item:nth-child(3) {
  animation-delay: 1.5s;
}

.image-item:nth-child(4) {
  animation-delay: 2.0s;
}

.image-item:nth-child(5) {
  animation-delay: 2.5s;
}

.image-item:nth-child(6) {
  animation-delay: 3.0s;
}

/* 动画定义 */
@keyframes fadeInUp {
  0% {
    opacity: 0;
    transform: translateY(30px);
  }

  100% {
    opacity: 1;
    transform: translateY(0);
  }
}
</style>